package com.knowledgeqa.system.controller;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义错误控制器
 * 替代Spring Boot默认的Whitelabel Error Page，提供更友好的错误处理
 */
@Controller
public class CustomErrorController implements ErrorController {

    /**
     * 处理所有未映射的请求路径，返回错误信息
     */
    @RequestMapping(value = "/error")
    public Object handleError(HttpServletRequest request) {
        // 获取错误状态码
        Object status = request.getAttribute("javax.servlet.error.status_code");
        
        // 判断请求是API请求还是页面请求
        String acceptHeader = request.getHeader("Accept");
        boolean isApiRequest = acceptHeader != null && acceptHeader.contains("application/json");
        
        if (status != null) {
            Integer statusCode = Integer.valueOf(status.toString());
            
            if (isApiRequest) {
                // API请求返回JSON格式的错误信息
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("status", statusCode);
                errorResponse.put("error", HttpStatus.valueOf(statusCode).getReasonPhrase());
                errorResponse.put("message", "请求的资源不存在或发生错误");
                return new ResponseEntity<>(errorResponse, HttpStatus.valueOf(statusCode));
            } else {
                // 页面请求返回错误页面
                ModelAndView modelAndView = new ModelAndView("WEB-INF/error");
                modelAndView.addObject("statusCode", statusCode);
                modelAndView.addObject("errorMessage", HttpStatus.valueOf(statusCode).getReasonPhrase());
                return modelAndView;
            }
        }
        
        // 默认返回404错误
        if (isApiRequest) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", 404);
            errorResponse.put("error", "Not Found");
            errorResponse.put("message", "请求的资源不存在");
            return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
        } else {
            ModelAndView modelAndView = new ModelAndView("WEB-INF/error");
            modelAndView.addObject("statusCode", 404);
            modelAndView.addObject("errorMessage", "Not Found");
            return modelAndView;
        }
    }
    
    /**
     * 获取错误路径
     */
    public String getErrorPath() {
        return "/error";
    }
}